package com.ny.service.impl;

import com.ny.mapper.CheckInRecordMapper;
import com.ny.mapper.MemberCardMapper;
import com.ny.mapper.MemberInfoMapper;
import com.ny.domain.CheckInRecordDO;
import com.ny.dto.CheckInDTO;
import com.ny.dto.PageResult;
import com.ny.query.CheckInQuery;
import com.ny.service.CheckInService;
import java.lang.Boolean;
import java.lang.Override;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ny.exception.BusinessException;
import java.util.List;
import com.ny.domain.MemberCardDO;
import com.ny.domain.MemberInfoDO;
import java.util.Date;

/**
 * 在线打卡管理模块的实现
 *
 * @author MSI-NB
 * @date 2025-03-08 13:14:38
 */
@Service
public class CheckInServiceImpl implements CheckInService {

    @Autowired
    private CheckInRecordMapper checkInRecordMapper;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private MemberCardMapper memberCardMapper;

    @Override
    public Boolean checkIn(CheckInDTO checkInDTO) {
        // 验证会员是否存在
        MemberInfoDO memberInfo = memberInfoMapper.selectById(checkInDTO.getMemberId());
        if (memberInfo == null) {
            throw new BusinessException("会员不存在");
        }
        // 验证会员卡是否有效
        MemberCardDO memberCard = memberCardMapper.selectByMemberId(checkInDTO.getMemberId());
        if (memberCard == null || memberCard.getExpirationDate().before(new Date())) {
            throw new BusinessException("会员卡已过期");
        }
        // 记录打卡信息
        CheckInRecordDO checkInRecordDO = new CheckInRecordDO();
        checkInRecordDO.setMemberId(checkInDTO.getMemberId());
        checkInRecordDO.setCheckInDate(new Date());
        checkInRecordDO.setCreateBy("system");
        checkInRecordDO.setCreateTime(new Date());
        checkInRecordDO.setUpdateBy("system");
        checkInRecordDO.setUpdateTime(new Date());
        int result = checkInRecordMapper.insert(checkInRecordDO);
        return result > 0;
    }

    @Override
    public PageResult<CheckInRecordDO> checkInRecords(CheckInQuery checkInQuery) {
        // 验证会员是否存在
        MemberInfoDO memberInfo = memberInfoMapper.selectById(checkInQuery.getMemberId());
        if (memberInfo == null) {
            throw new BusinessException("会员不存在");
        }
        // 查询会员打卡记录
        List<CheckInRecordDO> records = checkInRecordMapper.selectByMemberId(checkInQuery.getMemberId(), (checkInQuery.getPageIndex() - 1) * checkInQuery.getPageSize(), checkInQuery.getPageSize());
        long totalRecords = checkInRecordMapper.countByMemberId(checkInQuery.getMemberId());
        long totalPages = totalRecords / checkInQuery.getPageSize() + (totalRecords % checkInQuery.getPageSize() > 0L ? 1L : 0L);
        PageResult<CheckInRecordDO> pageResult = new PageResult<CheckInRecordDO>(totalRecords, totalPages, checkInQuery.getPageIndex(), checkInQuery.getPageSize(),records);
        return pageResult;
    }
}
